//
//  LeftViewController.m
//  AutoHome
//
//  Created by wqh on 15-5-21.
//  Copyright (c) 2015年 Wqh. All rights reserved.
//

#import "LeftViewController.h"

#import "AppDelegate.h"
#import "SearchResultViewController.h"
#import "SearchResultCell.h"

#define kSearchResultCellId @"SearchResultCellId"
#define kSearchHistory @"searchHistory"

@interface LeftViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic) NSMutableArray *dataArr;

@end

@implementation LeftViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self createSearchBar];
    [self createTableView];
    [self initData];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [[NSUserDefaults standardUserDefaults] setObject:self.dataArr forKey:kSearchHistory];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    self.tableView.alpha = 0;
    
}

#pragma mark - initData
- (void)initData {
    self.dataArr = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:kSearchHistory]];
    if (self.dataArr.count > 0) {
        [self.tableView reloadData];
    }
}

#pragma mark - showUI
- (void)createSearchBar {
    self.searchBar.frame = CGRectMake(10, 60, kScreenWidth-80, 44);
    self.searchBar.translucent = YES;
    self.searchBar.placeholder = @"输入关键字搜索";
    self.searchBar.delegate = self;
    self.searchBar.showsCancelButton = YES;
    self.searchBar.alpha = 0.9;


}
- (void)createTableView {
    self.tableView.frame = CGRectMake(10, 60+44, kScreenWidth-80, kScreenHeight-88-44-30);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.rowHeight = 30;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SearchResultCell" bundle:nil] forCellReuseIdentifier:@"SearchResultCellId" ];
    self.tableView.alpha = 0;
}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    return YES;
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    if (self.dataArr.count>0) {
        [UIView animateWithDuration:0.6 animations:^{
            self.tableView.alpha = 0.9;
        }];
    }
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    return YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
//    self.tableView.alpha = 0;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar resignFirstResponder];
    self.searchBar.text = nil;
    [UIView animateWithDuration:0.6 animations:^{
        self.tableView.alpha = 0;
    }];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    YRSideViewController *sideViewController =  [((AppDelegate*)[[UIApplication sharedApplication] delegate]) sideViewController];
    
    SearchResultViewController *vc = [[SearchResultViewController alloc] init];
    
    vc.searchStr = self.searchBar.text;
    
    [sideViewController.rootViewController.childViewControllers[0] pushViewController:vc animated:YES];
    
    [sideViewController hideSideViewController:YES];
    
    [self addSearchHistory:self.searchBar.text];
    
    self.searchBar.text = nil;
    
}

- (void)addSearchHistory:(NSString *)str {
        int i = 0;
    for (NSString *s in self.dataArr) {
        
        if ([str isEqualToString:s]) {
            [self.dataArr removeObjectAtIndex:i];
        }
        i++;
    }
    [self.dataArr insertObject:str atIndex:0];
    [self.tableView reloadData];
   
}


#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchResultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchResultCellId" forIndexPath:indexPath];
    cell.resultLabel.text = self.dataArr[indexPath.row];
    return cell;
}



- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 30);
//    headerView.backgroundColor = [UIColor clearColor];
    headerView.backgroundColor = [UIColor customGrayColor];
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(15, 2, 80, 20);
    label.text = @"搜索历史";
    label.textColor = [UIColor blackColor];
    label.font = [UIFont boldSystemFontOfSize:14];
    [headerView addSubview:label];
    
    return headerView;
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc] init];
    footerView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 30);
    footerView.backgroundColor = [UIColor customGrayColor];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"清除历史记录 × " forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    button.center = footerView.center;
    button.titleLabel.font = [UIFont boldSystemFontOfSize:13];
    button.bounds = CGRectMake(0, 0, 100, 30);
    [button addTarget:self action:@selector(removeSearchHistory:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:button];
    return footerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YRSideViewController *sideViewController =  [((AppDelegate*)[[UIApplication sharedApplication] delegate]) sideViewController];
    
    SearchResultViewController *vc = [[SearchResultViewController alloc] init];
    
    vc.searchStr = self.dataArr[indexPath.row];
    
    [sideViewController.rootViewController.childViewControllers[0] pushViewController:vc animated:YES];
    
    [sideViewController hideSideViewController:YES];
    
    self.searchBar.text = nil;
    [self addSearchHistory:self.dataArr[indexPath.row]];
}

- (void)removeSearchHistory:(UIButton *)button {
    [self.dataArr removeAllObjects];
    [self.tableView reloadData];
    self.tableView.alpha = 0;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.searchBar resignFirstResponder];
    self.tableView.alpha = 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
